package com.financing.wap.service.payment.baofoo;



import java.text.SimpleDateFormat;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.financing.wap.service.payment.baofoo.model.BaofooConfig;
import com.financing.wap.service.payment.baofoo.model.FpPaymentbaofoorsp;
import com.financing.wap.service.payment.baofoo.util.HttpRequestUtil;
import com.financing.wap.service.payment.baofoo.util.SecurityUtil;
import com.financing.wap.service.payment.baofoo.util.rsa.RsaCodingUtil;

/**
 * 天天基金支付交易 和 订单查询 demo
 * @author Administrator
	   @Version1.0.0
	   @Description  对接测试环境demo

	   	 具体字段含义参照 接口文档

	 加密说明： 发送交易报文时必须加密，加密步骤：先Base64进行加密，然后再使用RSA对Base64加密的串进行第二次加密
	 解密说明：宝付返回密文，需要先RSA进行解密，然后再用Base64对RSA解密的串再次解密获取原文      	 

 *
 */
public class BaofooService {

	private static String version = "4.0.0.0";//支付版本号
	private static String txn_type = "0431";// 交易类型
	private static String id_card_type="01";//身份证类型，默认固定值
	private static String data_type = "json";//报文形式，json、xml
	
	public static void main(String[] args){
		/*String orderId = "juyoubaotest002";//商户订单号
		String cardno = "6212261001038098049";//银行卡号
		String phone = "18616559102";//银行预留手机号
		String orderAmount = "1";//交易金额
		String idcardno = "532424198107241651";//身份证号
		String userRealName = "史云来";//姓名
		String bankcode = "ICBC";//银行编码
		BaofooService.sendQkPay(orderId, cardno, bankcode, phone, idcardno, userRealName, orderAmount);*/
		
		BaofooService.sendQuery("juyoubaotest002");
	}
	
	/**
	 * 7、代收类交易【直接】
	 */
	public static FpPaymentbaofoorsp sendQkPay(String smsCode ,String orderId, String cardno, String bankcode, String phone, String idcardno, 
			String userRealName, String orderAmount,String bind_id,String additionalInfo) {
		String txn_sub_type = "04";//子交易类型
		//获取要发送的请求数据
		String data_content = sendQkPayReal(smsCode,txn_sub_type, orderId, cardno, phone, idcardno, userRealName,  "", 
				"", bankcode, orderAmount, bind_id,additionalInfo, "");
		//发送支付交易请求，07标识交易子类型
		String backStr = send(txn_sub_type, data_content);
		
		FpPaymentbaofoorsp result = JSON.parseObject(backStr, new TypeReference<FpPaymentbaofoorsp>() {});
		
		return result;
	}

	/**
	 * 6、交易状态查询类交易
	 */

	public static FpPaymentbaofoorsp sendQuery(String orderId) {
		String txn_sub_type = "06";// 交易子类
		String data_content = sendQueryReal(txn_sub_type, orderId, "", "");
		String backStr = send(txn_sub_type, data_content);
		
		FpPaymentbaofoorsp result = JSON.parseObject(backStr, new TypeReference<FpPaymentbaofoorsp>() {});
		
		return result;
	}

	// =================================================================================================================
	/**
	 * 发送交易
	 * 
	 * @param data_content
	 * 
	 * 
	 */
	private static String send(String txn_sub_type, String data_content) {
		/*String keyPath = "D:/work/juyoubao/jybcore/src/main/java/com/lanmosoft/service/payment/baofoo/cer/bfkey_100000749@@100000933.pfx";
		String keyPwd = "100000749_272769";
		String cerPath = "D:/work/juyoubao/jybcore/src/main/java/com/lanmosoft/service/payment/baofoo/cer/bfkey_100000749@@100000933.cer";
		String member_id = "100000749";
		String terminal_id = "100000933";//
		String domain = "https://tgw.baofoo.com/cutpayment/api/backTransRequest";*/
		
		String member_id = BaofooConfig.getInstance().getMember_id();//商户号
		String terminal_id = BaofooConfig.getInstance().getTerminal_id();//终端号
		String domain = BaofooConfig.getInstance().getBackTransRequest();//支付、查询请求地址
		
		String cerPath = BaofooService.class.getClassLoader().getResource(BaofooConfig.getInstance().getCerPath()).getPath();//宝付支付公钥
		String keyPath = BaofooService.class.getClassLoader().getResource(BaofooConfig.getInstance().getKeyPath()).getPath();//商户私钥
		String keyPwd = BaofooConfig.getInstance().getKeyPwd();//商户私钥密码
		
		try {
			// 商户私钥加密。先base64 加密，然后 RSA私钥加密

			data_content = RsaCodingUtil.encryptByPriPfxFile(SecurityUtil.Base64Encode(data_content), keyPath, keyPwd);
			String params = "version=%s&member_id=%s&terminal_id=%s&txn_type=%s&txn_sub_type=%s&data_type=%s&data_content=%s";
			params = String.format(params, version, member_id, terminal_id, txn_type, txn_sub_type, data_type, data_content);
			// ================ POST 提交 =====================
			System.out.println("请求报文（加密）：" + params);
			String responseStr = HttpRequestUtil.sendHttpsPost(domain, params, "UTF-8").toString();
			// ================ POST 提交 =====================
			// 宝付回复密文。。先公钥解密，后base64解密
			responseStr = RsaCodingUtil.decryptByPubCerFile(responseStr, cerPath);
			String result = SecurityUtil.Base64Decode(responseStr);
			System.out.println("[解密响应报文]:" + result);
			
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 该方法用于组装支付交易报文    仅供参考
	 * @param txn_sub_type 交易子类型
	 * @param trans_id 商户订单号
	 * @param acc_no 银行卡号
	 * @param mobile 银行卡注册手机号
	 * @param id_card 身份证号
	 * @param id_holder 持卡人姓名
	 * @param valid_date 卡有效期，非必填
	 * @param valid_no 卡三位安全码，非必填
	 * @param pay_code 银行编码
	 * @param txn_amt 订单金额，分
	 * @param additional_info 附加信息
	 * @param req_reserved 指定保留的字段
	 * @return
	 */
	private static String sendQkPayReal(String smsCode,String txn_sub_type, String trans_id, String acc_no, String mobile, String id_card, String id_holder,  
			String valid_date, String valid_no, String pay_code, String txn_amt, String bind_id, String additional_info, 
			String req_reserved) {
		//String member_id = "100000749";
		//String terminal_id = "100000933";
		
		String member_id = BaofooConfig.getInstance().getMember_id();//商户号
		String terminal_id = BaofooConfig.getInstance().getTerminal_id();//终端号
		
		String trade_date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		StringBuilder sb = new StringBuilder();

		sb.append("{"); 
		sb.append("\"txn_sub_type\":\"" + txn_sub_type + "\"");
		sb.append(",\"biz_type\":\"0000\"");// 接入类型默认0000
		sb.append(",\"terminal_id\":\"" + terminal_id + "\"");
		sb.append(",\"member_id\":\"" + member_id + "\"");
		sb.append(",\"bind_id\":\"" + bind_id + "\"");
		sb.append(",\"pay_code\":\"" + pay_code + "\"");
		sb.append(",\"acc_no\":\"" + acc_no + "\"");
		sb.append(",\"id_card_type\":\"" + id_card_type + "\"");
		sb.append(",\"id_card\":\"" + id_card + "\"");
		sb.append(",\"id_holder\":\"" + id_holder + "\"");
		sb.append(",\"mobile\":\"" + mobile + "\"");
		sb.append(",\"valid_date\":\"" + valid_date + "\"");
		sb.append(",\"valid_no\":\"" + valid_no + "\"");
		sb.append(",\"trans_serial_no\":\"" + member_id + "" + trade_date + "\"");
		sb.append(",\"trans_id\":\"" + trans_id + "\"");
		sb.append(",\"txn_amt\":\"" + txn_amt + "\"");
		sb.append(",\"sms_code\":\"" + smsCode + "\"");
		sb.append(",\"trade_date\":\"" + trade_date + "\"");
		sb.append(",\"additional_info\":\"" + additional_info + "\"");
		sb.append(",\"req_reserved\":\"" + req_reserved + "\"");
		sb.append("}");

		System.out.println("请求xml报文："+sb.toString());
		return sb.toString();
	}

	/**
	 * 该方法用于组装交易查询报文  仅供参考
	 * @param txn_sub_type  交易子类型
	 * @param orig_trans_id 宝付交易流水
	 * @param additional_info
	 * @param req_reserved
	 * @return
	 */
	private static String sendQueryReal(String txn_sub_type, String orig_trans_id, String additional_info, String req_reserved) {
		//String member_id = "100000749";
		//String terminal_id = "100000933";
		String member_id = BaofooConfig.getInstance().getMember_id();//商户号
		String terminal_id = BaofooConfig.getInstance().getTerminal_id();//终端号
		String trade_date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"txn_sub_type\":\"" + txn_sub_type + "\"");
		sb.append(",\"biz_type\":\"0000\"");// 接入类型默认0000
		sb.append(",\"terminal_id\":\"" + terminal_id + "\"");
		sb.append(",\"member_id\":\"" + member_id + "\"");
		sb.append(",\"trans_serial_no\":\"" + member_id + "" + trade_date + "\"");
		sb.append(",\"orig_trans_id\":\"" + orig_trans_id + "\"");
		sb.append(",\"trade_date\":\"" + trade_date + "\"");
		sb.append(",\"additional_info\":\"" + additional_info + "\"");
		sb.append(",\"req_reserved\":\"" + req_reserved + "\"");
		sb.append("}");

		return sb.toString();
	}
	
	/**
	 * 8、发送短信类交易
	 */
	public static FpPaymentbaofoorsp sendSMS(String orderId, String cardno, String bankcode, String phone, String idcardno, 
			String userRealName, String orderAmount,String bind_id,String additionalInfo) {
		String txn_sub_type = "05";//子交易类型
		//获取要发送的请求数据
		String data_content = sendSMSReal(txn_sub_type, orderId, cardno, phone, orderAmount,bind_id, additionalInfo, "");
		//发送支付交易请求，05标识交易子类型
		String backStr = send(txn_sub_type, data_content);
		System.out.println("返回信息sendSMS："+backStr);
		FpPaymentbaofoorsp result = JSON.parseObject(backStr, new TypeReference<FpPaymentbaofoorsp>() {});
		
		return result;
	}
	
	/**
	 * 该方法用于组装发送短信类交易报文    仅供参考
	 * @param txn_sub_type 交易子类型
	 * @param trans_id 商户订单号
	 * @param acc_no 银行卡号
	 * @param mobile 银行卡注册手机号
	 * @param pay_code 银行编码
	 * @param txn_amt 订单金额，分
	 * @param additional_info 附加信息
	 * @param req_reserved 指定保留的字段
	 * @return
	 */
	private static String sendSMSReal(String txn_sub_type, String trans_id, String acc_no, String mobile,String txn_amt,String bind_id,  String additional_info, String req_reserved) {
		
		String member_id = BaofooConfig.getInstance().getMember_id();//商户号
		String terminal_id = BaofooConfig.getInstance().getTerminal_id();//终端号
		
		String trade_date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		StringBuilder sb = new StringBuilder();

		sb.append("{"); 
		sb.append("\"txn_sub_type\":\"" + txn_sub_type + "\"");
		sb.append(",\"biz_type\":\"0000\"");// 接入类型默认0000
		sb.append(",\"terminal_id\":\"" + terminal_id + "\"");
		sb.append(",\"member_id\":\"" + member_id + "\"");
		sb.append(",\"trans_serial_no\":\"" + member_id + "" + trade_date + "\"");
		sb.append(",\"trans_id\":\"" + trans_id + "\"");
		sb.append(",\"acc_no\":\"" + acc_no + "\"");
		sb.append(",\"mobile\":\"" + mobile + "\"");
		sb.append(",\"bind_id\":\"" + bind_id + "\"");
		sb.append(",\"txn_amt\":\"" + txn_amt + "\"");
		sb.append(",\"next_txn_sub_type\":\"" + "04" + "\"");
		sb.append(",\"trade_date\":\"" + trade_date + "\"");
		sb.append(",\"additional_info\":\"" + additional_info + "\"");
		sb.append(",\"req_reserved\":\"" + req_reserved + "\"");
		sb.append("}");

		System.out.println("请求xml报文："+sb.toString());
		return sb.toString();
	}
}
